package com.longxi.tianjintianbao.ui.presenter.complaint;

import android.content.Intent;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.View;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.BaseResponse;
import com.longxi.tianjintianbao.api.response.HttpResult;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.model.Personnel;
import com.longxi.tianjintianbao.model.complaint.Complaint;
import com.longxi.tianjintianbao.model.complaint.ComplaintFollow;
import com.longxi.tianjintianbao.ui.activity.complaint.SaveComplaintActivity;
import com.longxi.tianjintianbao.ui.activity.repair.UpdateRepairContentActivity;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.dialog_fragment.ComplaintDealDialogFragment;
import com.longxi.tianjintianbao.ui.presenter.repair.UpdateRepairContentAtPresenter;
import com.longxi.tianjintianbao.ui.view.complaint.IComplaintDetailAtView;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.longxi.tianjintianbao.utils.NListRefresh;
import com.longxi.tianjintianbao.widget.AddComplaintFollowDialog;
import com.longxi.tianjintianbao.widget.MaintenancePlanDialog;
import com.longxi.tianjintianbao.widget.UpdateComplaintDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 70339 on 2018/5/3.
 * 代码无八阿哥
 * 阿弥陀佛
 */
public class ComplaintDetailAtPresenter extends BasePresenter<IComplaintDetailAtView> {

    private Complaint complaint;

    public void setBar() {
        mContext.setTitle("投诉详情");
        mContext.setTvLeft(MyUtils.getString(R.string.back));
    }

    public void getComplaint(){
        JSONObject object = new JSONObject();
        try {
            object.put("billid", mContext.getIntent().getStringExtra(AppConst.BILLID));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mContext.showWaitingDialog(MyUtils.getString(R.string.load));
        ApiRetrofit.getInstance().getComplaintDetail(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<Complaint>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(HttpResult<Complaint> result) {
                mContext.hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    return;
                }

                complaint = result.getData().get(0);
                setComplaint();
                getComplaintFollow();
            }
        });
    }

    //将列表页的数据展示
    public void setComplaint(){
        getView().getTvDate().setText(complaint.getComplaintdate());
        if(!complaint.getPerson().isEmpty()){
            getView().getTvStatus().setText("接单人—" + complaint.getPerson());
        }
        getView().getTvName().setText("业主—" + complaint.getName() + "/" + complaint.getPhone());
        getView().getTvAddress().setText(complaint.getAddress());
        getView().getTvTaskContent().setText("单据类别: " + complaint.getBilltype() + "\n单据内容: " + complaint.getContent());


        SpannableStringBuilder builder = new SpannableStringBuilder("投诉处理: " + complaint.getState());
        ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED);
        builder.setSpan(redSpan, 5, builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        getView().getTvDealState().setText(builder);

        if(!"".equals(complaint.getHandledate())){
            getView().getTvDealDate().setVisibility(View.VISIBLE);
            getView().getTvDealResult().setVisibility(View.VISIBLE);
            getView().getTvDealDate().setText("处理时间: " + complaint.getHandledate());

            String handletype = "上门";
            if("0".equals(complaint.getHandletype())){
                handletype = "电话";
            }
//            getView().getTvDealResult().setText("处理方式: " + handletype +"\n处理内容: " + complaint.getResult());
            getView().getTvDealResult().setText("处理内容: " + complaint.getResult());
        }

        getView().getTvDealOther().setText("投报状态: " + complaint.getReportstate() + "\n投报性质: " + complaint.getReportnature() + "\n投保类型: " + complaint.getReporttype()+ "\n投保类别: " + complaint.getReportcategory());

        showBtn();

    }

    public void showBtn(){
        mContext.setTvRight("");
        switch (complaint.getState()) {
            case "未立项":
                if("建议".equals(complaint.getBilltype()) || "咨询".equals(complaint.getBilltype())){
                    getView().getBtnComplete().setVisibility(View.VISIBLE);
                    getView().getBtnComplete().setText("确认立项");
                }else{
                    if("有效投诉".equals(complaint.getReportstate())){
                        getView().getBtnComplete().setVisibility(View.VISIBLE);
                        getView().getBtnComplete().setText("确认立项");
                    }else{
                        getView().getBtnComplete().setVisibility(View.GONE);
                    }
                }
                getView().getLlState().setVisibility(View.VISIBLE);
                getView().getBtnPause().setVisibility(View.VISIBLE);
                getView().getBtnPause().setText("调整信息");
                break;
            case "未接单":
                getView().getLlState().setVisibility(View.VISIBLE);
                getView().getBtnComplete().setVisibility(View.VISIBLE);
                getView().getBtnComplete().setText("立即接单");
                break;
            case "处理中":
                getView().getLlState().setVisibility(View.VISIBLE);
                getView().getBtnComplete().setVisibility(View.VISIBLE);
                getView().getBtnComplete().setText("立即处理");
                getView().getLlState().setVisibility(View.VISIBLE);
                getView().getBtnPause().setVisibility(View.VISIBLE);
                getView().getBtnPause().setText("投诉跟进");
                mContext.setTvRight("处理方案");
                break;
            default:
                getView().getLlState().setVisibility(View.GONE);
                break;
        }
    }

    public void onCommit(){
        switch (complaint.getState()) {
            case "未立项":
                //立项
                getDepartment(false);
                break;
            case "未接单":
                //接单
                receiveComplaint();
                break;
            case "处理中":
                //处理
                Intent intent = new Intent(mContext, SaveComplaintActivity.class);
                intent.putExtra(AppConst.BILLID, complaint.getBillid());
                mContext.startActivityForResult(intent, AppConst.IntentRequstCode.ACTIVITY_SAVE_COMPLAINT);
                break;
            default:
                getView().getLlState().setVisibility(View.GONE);
                break;
        }
    }

    public void btnComplete(){
        showComplaintDealDialogFragment();
    }

    public void saveComplaint(String type, String result){
        mContext.showWaitingDialog(MyUtils.getString(R.string.upload));
        JSONObject object = new JSONObject();
        try {
            object.put("billid", complaint.getBillid());
            object.put("userid", MyApplication.loginUser.userid);
            object.put("handletype", type);
            object.put("result", result);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().saveComplaint(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse result) {
                mContext.hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    return;
                }
                MyUtils.showToast(result.getMsg());
                mContext.setResult(mContext.RESULT_OK);
                mContext.finish();
            }
        });
    }

    public ComplaintDetailAtPresenter(BaseActivity context) {
        super(context);
    }

    ComplaintDealDialogFragment complaintDealDialogFragment;
    public void showComplaintDealDialogFragment() {
        complaintDealDialogFragment = new ComplaintDealDialogFragment();
        complaintDealDialogFragment.show(mContext.getFragmentManager(), "ComplaintDealDialogFragment");
    }

    UpdateComplaintDialog.Builder maintenancePlanDialog;

    /**
     * 弹出投报信息调整框
     */
    public void updateComplaint() {
        if(maintenancePlanDialog != null){
            maintenancePlanDialog.show();
        }else{
            maintenancePlanDialog = new UpdateComplaintDialog.Builder(mContext);
            maintenancePlanDialog
            .setProperty(new UpdateComplaintDialog.OnClickListener() {
                @Override
                public void onClick(String reportstate, String reportnature, String reporttype, String reportcategory) {
                    complaint.setReportstate(reportstate);
                    complaint.setReportnature(reportnature);
                    complaint.setReporttype(reporttype);
                    complaint.setReportcategory(reportcategory);

                    maintenancePlanDialog.dismiss();
                    toUpdateComplaint();
                }
            })
            .create()
            .show();
        }
        maintenancePlanDialog.setRadioGroup(complaint.getReportstate(), complaint.getReportnature(), complaint.getReporttype(), complaint.getReportcategory());
    }

    public void toUpdateComplaint(){
        mContext.showWaitingDialog(MyUtils.getString(R.string.upload));
        JSONObject object = new JSONObject();
        try {
            object.put("billid", complaint.getBillid());
            object.put("userid", MyApplication.loginUser.userid);
            object.put("reportstate", complaint.getReportstate());
            object.put("reportnature", complaint.getReportnature());
            object.put("reporttype", complaint.getReporttype());
            object.put("reportcategory", complaint.getReportcategory());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().updateComplaint(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse result) {
                mContext.hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    return;
                }
                getView().getTvDealOther().setText("投报状态: " + complaint.getReportstate() + "\n投报性质: " + complaint.getReportnature() + "\n投保类型: " + complaint.getReporttype()+ "\n投保类别: " + complaint.getReportcategory());
                showBtn();
                mContext.setResult(mContext.RESULT_OK);
            }
        });
    }

    private List<Personnel> personnel;
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != mContext.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case AppConst.IntentRequstCode.ACTIVITY_PERSONNEL:
                personnel = (List<Personnel>) data.getSerializableExtra(AppConst.PERSONNEL_LISTINTENT);
                trojectComplaint(personnel.get(0));
                break;
            case AppConst.IntentRequstCode.ACTIVITY_SAVE_COMPLAINT:
                getComplaint();
                break;
        }
    }

    public void trojectComplaint(Personnel personnel){
        mContext.showWaitingDialog(MyUtils.getString(R.string.upload));
        JSONObject object = new JSONObject();
        try {
            object.put("billid", complaint.getBillid());
            object.put("userid", MyApplication.loginUser.userid);
            object.put("handid", personnel.getUserid());
            object.put("handname", personnel.getUsername());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().projectComplaint(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse result) {
                mContext.hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    return;
                }
                mContext.setResult(mContext.RESULT_OK);
                getComplaint();
            }
        });
    }

    public void receiveComplaint(){
        mContext.showWaitingDialog(MyUtils.getString(R.string.upload));
        JSONObject object = new JSONObject();
        try {
            object.put("billid", complaint.getBillid());
            object.put("userid", MyApplication.loginUser.userid);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().receiveComplaint(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse result) {
                mContext.hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    return;
                }
                mContext.setResult(mContext.RESULT_OK);
                getComplaint();
            }
        });
    }

    AddComplaintFollowDialog.Builder addComplaintFollowDialog;
    /**
     * 弹出投报信息调整框
     */
    public void addComplaintFollowDialog() {
        if(addComplaintFollowDialog != null){
            addComplaintFollowDialog.show();
        }else{
            addComplaintFollowDialog = new AddComplaintFollowDialog.Builder(mContext);
            addComplaintFollowDialog
            .setTitle("添加投诉跟进记录")
            .setListener(new AddComplaintFollowDialog.OnClickListener() {
                @Override
                public void onClick(String followcontent) {
                    addComplaintFollow(followcontent);
                    addComplaintFollowDialog.dismiss();
                }
            })
            .create()
            .show();
        }
    }

    public void addComplaintFollow(String followcontent){
        mContext.showWaitingDialog(MyUtils.getString(R.string.upload));
        JSONObject object = new JSONObject();
        try {
            object.put("billid", complaint.getBillid());
            object.put("userid", MyApplication.loginUser.userid);
            object.put("followcontent", followcontent);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().addComplaintFollow(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse result) {
                mContext.hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    return;
                }
                mContext.setResult(mContext.RESULT_OK);
                //请求列表数据
                getComplaintFollow();
            }
        });
    }

    @Override
    public void detachView() {
        super.detachView();
        this.personnel = null;
        this.complaint = null;
        this.maintenancePlanDialog = null;
    }

    public void onUpdate() {
        switch (complaint.getState()) {
            case "未立项":
                //调整信息
                updateComplaint();
                break;
            case "未接单":
                //接单
                break;
            case "处理中":
                //处理
                addComplaintFollowDialog();
                break;
            default:
                getView().getLlState().setVisibility(View.GONE);
                break;
        }
    }

    public void getComplaintFollow(){
        mContext.showWaitingDialog(MyUtils.getString(R.string.upload));
        JSONObject object = new JSONObject();
        try {
            object.put("billid", mContext.getIntent().getStringExtra(AppConst.BILLID));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().getComplaintFollow(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<ComplaintFollow>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(HttpResult<ComplaintFollow> result) {
                mContext.hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    return;
                }
                setComplaintFollow(result.getData());
                mContext.setResult(mContext.RESULT_OK);
                //请求列表数据
            }
        });
    }

    public void setComplaintFollow(List<ComplaintFollow> list){
        StringBuffer stringBuffer = new StringBuffer();
        for (ComplaintFollow complaintFollow : list) {
            stringBuffer.append("\n跟进人:" + complaintFollow.getFollower());
            stringBuffer.append("   跟进部门:" + complaintFollow.getFollowdept());
            stringBuffer.append("\n跟进日期:" + complaintFollow.getFollowdate());
            stringBuffer.append("\n跟进内容:" + complaintFollow.getFollowcontent() + "\n");
        }
        getView().getTvComplaintFollow().setText(stringBuffer);
    }

    AddComplaintFollowDialog.Builder complaintProgrammeDialog;
    /**
     * 弹出投报信息调整框
     */
    public void complaintProgrammeDialog() {
        if(complaintProgrammeDialog != null){
            complaintProgrammeDialog.show();
        }else{
            complaintProgrammeDialog = new AddComplaintFollowDialog.Builder(mContext);
            complaintProgrammeDialog
            .setTitle("添加投诉处理方案")
            .setListener(new AddComplaintFollowDialog.OnClickListener() {
                @Override
                public void onClick(String programme) {
                    complaintProgramme(programme);
                    complaintProgrammeDialog.dismiss();
                }
            })
            .create()
            .show();
        }
    }

    public void complaintProgramme(String programme) {
        mContext.showWaitingDialog(MyUtils.getString(R.string.upload));
        JSONObject object = new JSONObject();
        try {
            object.put("billid", mContext.getIntent().getStringExtra(AppConst.BILLID));
            object.put("userid", MyApplication.loginUser.userid);
            object.put("programme", programme);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().complaintProgramme(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse result) {
                mContext.hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    return;
                }
                MyUtils.showToast("添加投诉处理方案成功");
            }
        });
    }
}
